from main.alarm.models import Alarm
from main.alarm.serializers import AlarmSerializer, AlarmCreateSerializer
from utils.json_response import SuccessResponse
from utils.viewset import CustomModelViewSet
from system.project.models import Channel

from utils.sign import SignAuthentication
from libs import json_response
from libs.parser import Argument, JsonParser
from rest_framework.decorators import api_view


@SignAuthentication
@api_view(['POST'])
def weixin_warn(request):
    params, error = JsonParser(
        Argument('project'),
        Argument('channel'),
        Argument('alarm_time'),
        Argument('title'),
        Argument('content'),
    ).parse(request.body)
    if not error:
        params.channel = Channel.objects.filter(channel_api=params.pop('channel')).first()
        Alarm.objects.create(**params)
    return json_response(error=error)


class AlarmModelViewSet(CustomModelViewSet):
    """
    微信报警信息 的CRUD视图
    """
    queryset = Alarm.objects.all()
    serializer_class = AlarmSerializer
    create_serializer_class = AlarmCreateSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return SuccessResponse(data=serializer.data, message="新增成功")
